package simple.runtime.components.impl.android;

import simple.runtime.android.MainActivity;
import simple.runtime.collections.意图;
import simple.runtime.components.广播接收器;
import simple.runtime.components.组件容器;
import simple.runtime.components.impl.组件Impl;
import simple.runtime.events.EventDispatcher;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Context;

/**
 * 广播接收器的实现。
 * 
 * @author 东子 xhwsd@qq.com
 */
public class 广播接收器Impl extends 组件Impl implements 广播接收器 {

  private BroadcastReceiver receiver;
  private String action;

  public 广播接收器Impl(组件容器 container) {
    super(container);
  }

  // 广播接收器 实现

  @Override
  public void 收到广播(意图 intent) {
    EventDispatcher.dispatchEvent(this, "收到广播", intent);
  }

  @Override
  public String 接受行为() {
    return action;
  }

  @Override
  public void 接受行为(String action) {
    // 注销广播
    if (receiver != null) {
      MainActivity.getContext().unregisterReceiver(receiver);
      receiver = null;
    }

    // 注册广播
    if (action != null && !action.isEmpty()) {
      receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          if (intent.getAction().equals(action)) {
            收到广播(new 意图(intent));
          }
        }
      };
      // 注册接收器
      MainActivity.getContext().registerReceiver(receiver, new IntentFilter(action));
    }
    this.action = action;
  }
}